package devbureau.servlet;

import devbureau.fstore.common.CustomerData;
import devbureau.fstore.common.OrderData;
import devbureau.fstore.common.StoreFactory;
import devbureau.fstore.common.load.FileWriter;
import devbureau.fstore.common.load.FileWriterFactory;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import static devbureau.servlet.Constants.ORDER_ID;
/**
 *
 * @author admin
 */
public class PrintPaymentServlet extends HttpServlet {
    private static final Logger log = Logger.getLogger(PrintPaymentServlet.class);

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          Integer orderId = Integer.valueOf(request.getParameter(ORDER_ID));
          String fileName = null;          
          try{
              OrderData order = StoreFactory.getStore().getOrder(orderId);
              CustomerData customer = order.getCustomer();
              fileName = saveOrderToExcel(order, customer);

              doDownload(request, response, fileName);
          }catch(Exception e){
              log.error("Can't download file with name["+fileName+"] for orderId["+orderId+"]. " + e.getMessage());
          }
    }

    public String saveOrderToExcel(OrderData order, CustomerData customer) {
        log.debug("saveOrderToExcel -> enter");
        String fileName = null;
        try {
            FileWriter fileWriter = FileWriterFactory.getFileWriter(FileWriterFactory.XLS);
            fileName = fileWriter.writeOrder(order, customer);
        }
        catch (Exception ex) {
            log.error("Error while writing order file to server", ex);
        }
        log.debug("saveOrder -> exit String: " + fileName);

        return fileName;
    }

    private void doDownload( HttpServletRequest request, HttpServletResponse response,
                             String fileName) throws IOException {
        File                file     = new File(fileName);
        int                 length   = 0;
        ServletOutputStream op       = response.getOutputStream();
        ServletContext      context  = getServletConfig().getServletContext();
        String              mimetype = context.getMimeType( fileName );

        response.setContentType( (mimetype != null) ? mimetype : "application/octet-stream" );
        response.setContentLength( (int)file.length() );
        response.setHeader( "Content-Disposition", "attachment; filename=\"" + fileName + "\"" );

        byte[] bbuf = new byte[1024];
        DataInputStream in = new DataInputStream(new FileInputStream(file));

        while ((in != null) && ((length = in.read(bbuf)) != -1)) {
            op.write(bbuf,0,length);
        }

        in.close();
        op.flush();
        op.close();
    }

}
